package com.wmzdq.aiservice.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.wmzdq.aiservice.constant.PlatformConstant;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.internal.platform.Platform;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.ai.deepseek.DeepSeekChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Path;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手，请根据用户提问回答！";
    private final ChatClient dashScopeChatClient;
    private final ChatClient deepseekChatClient;

//    @Qualifier("dashscopeChatModel")


    // 也可以使用如下的方式注入 ChatClient
    public TestController(@Qualifier("dashscopeChatModel") DashScopeChatModel chatModel,
    @Qualifier("deepSeekChatModel") DeepSeekChatModel deepseekChatModel) {
        this.dashScopeChatClient = ChatClient.builder(chatModel)
                .defaultSystem(DEFAULT_PROMPT)
                // TODO
                // 实现 Chat Memory 的 Advisor
                // 在使用 Chat Memory 时，需要指定对话 ID，以便 Spring AI 处理上下文。
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                )
//				  实现 Logger 的 Advisor
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(
                        DashScopeChatOptions.builder()
                                .withTopP(0.7).withModel("qwen-vl-max-latest").withMultiModel(true)
                                .build()
                )
                .build();

        this.deepseekChatClient= ChatClient.builder(deepseekChatModel)
                // 实现 Logger 的 Advisor
                .defaultAdvisors(new SimpleLoggerAdvisor())
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(DeepSeekChatOptions.builder().temperature(0.7d).topP(0.7).build()).build();
    }

    @GetMapping("/simple/chat")
    public String simpleChat(@RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？")String query,@RequestParam(value="model",defaultValue = PlatformConstant.DEEPSEEK)String model) {
        log.info("简单请求");
        if(model.contains(PlatformConstant.DEEPSEEK)){
            return deepseekChatClient.prompt(query).call().content();
        }else{
            return dashScopeChatClient.prompt(query).call().content();
        }
    }


    @GetMapping("/supperLotto")
    public String supperLotto(@RequestParam(value="path")String path){
        log.info("识别图片地址："+path);
        return dashScopeChatClient.prompt().user(u->u.text("不要输出解析过程，只要给我最终结果，" +
                "如果是多期票，请预测一下未显示在票面的期数，并使用如下的json格式返回这个彩票数据," +
                "注意key值不要有错,没有提到的数据不要返回  " +
                "```{draw: '预测彩票包含的所有开奖期数，多期用数组返回',addon: Y表示追加N不追加,miltiple：倍数," +
                "front：前区号码， back: 后区号码,nums:几期，一期显示1，2期显示2等，id:彩票号码}```")
                .media(MimeTypeUtils.IMAGE_JPEG, new PathResource(path))).call().content();

    }


    @PostMapping("/search/chat")
    public String searchChat(@RequestBody String input){
        JSONObject object= JSON.parseObject(input);
        String query=object.getString("query");
        log.info("联网查询，查询内容："+query);
        var searchOptions = DashScopeApi.SearchOptions.builder()
                .forcedSearch(true)
                .enableSource(true)
                .searchStrategy("pro")
                .enableCitation(true)
                .citationFormat("[<number>]")
                .build();
        var options = DashScopeChatOptions.builder()
                .withEnableSearch(true)
               // .withModel(DashScopeApi.ChatModel.DEEPSEEK_V3.getValue())
                .withSearchOptions(searchOptions)
                .withTemperature(0.7)
                .build();


        return dashScopeChatClient.prompt(query).options(options).call().content();
    }
}
